<?php

class doarticle {

    public function tasks() {
        $lock_key = "tasks_lock_time";
        $bool = mredis::get($lock_key);
        if (empty($bool)) {
            try {
                mredis::setnxe($lock_key, 1, 60);
                $this->toDo();
                mredis::del($lock_key);
            } catch (Exception $ex) {
                logging_run('任务处理出错：' . $ex->getMessage());
                mredis::del($lock_key);
            }
        } else {
            logging_run('任务正在处理中');
        }
    }

    public function toDo() {
        $limit = 200;
        $classes = db::select("select a.* from `classlist` as a left join `yuming` as y ON a.yuming_id=y.id where y.autoCatch=1 and status=1 order by id desc limit 3000");
        $toUrl = REMOTEAPI . "/dataapi/content";
        $data = db::select("select * from `caiji` where status=0 limit {$limit}");
        $yuming_arr = [];
        $lcount = 0;
        $congCount = 0;
        $errorCount = 0;
        foreach ($data as $value) {
            $aid = $value['id'];
            try {
                if (empty($value['title']) || empty($value['content'])) {
                    db::query("update `caiji` set status=2 where id='$aid'");
                    $errorCount++;
                    continue;
                }
                if (!empty($value['yuming_id'])) {
                    $yuming = db::getfield("select * from `yuming` where id=".$value['yuming_id']);
                    if(empty($yuming)) {
                        logging_run("域名ID:".$value['yuming_id']."未找到,数据节点ID:".$value['id']);
                        continue;
                    }elseif(intval($yuming['autoCatch'])==0) {
                        logging_run("域名ID:".$value['yuming_id']."未开启自动任务,数据节点ID:".$value['id']);
                        continue;
                    }
                    $classes = db::select("select * from `classlist` where yuming_id=" . $value['yuming_id'] . " and  status=1 order by id desc limit 1000");
                }
                $res_class = $this->find_class($value['class'], $classes);
                $yuming_id = $res_class['yuming_id'];
                $class = $res_class['ename'];
                $title = $oldtitle = $value['title'];

                //文章查重
                if (!in_array($yuming_id, $yuming_arr)) {
                    $yuming_arr[] = $yuming_id;
                }
                $title = trim($title);
                $article = db::find("select * from `content_{$yuming_id}` where oldtitle='$oldtitle'");
                if ($article) {
                    $congCount++;
                    db::query("update `caiji` set status=2 where id='$aid'");
                    continue;
                }

                $filecontent = str_replace(array("<p>(点击图片看大图)</p>", "显示全文"), "", $value['content']);
                //过滤原标题
                $filecontent = str_replace("原标题：", "", $filecontent);
                $filecontent = preg_replace("/20\d{2}-\d{2}-\d{2} \d{2}:\d{2}/i", "", $filecontent);
                $filecontent = str_replace("</p></p>", "</p>", $filecontent);
                $filecontent = str_replace("<p><p align=\"center\">", "<p align=\"center\">", $filecontent);
                $filecontent = preg_replace("/<a[^>]*>(.*?)<\/a>/is", "$1", $filecontent); //去除A标签
                $filecontent= preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $filecontent);//去除IMG标签
                $filecontent= preg_replace('/<script[\s\S]*?<\/script>/i', '', $filecontent);//去除script标签
                $filecontent = preg_replace("/上一页.*?下一页/", "", $filecontent);
                //获取描述内容
                $description = strip_tags($filecontent);
                $description = trim($description);
                $description = str_replace(array(" ", " "), "", $description);
                $description = mb_substr($description, 0, 150, 'utf-8');
                $description = addslashes($description);

                //图片处理
                //$filecontent = yumi::convert_images_patch($filecontent, '', $toUrl, $yuming_id);
                // 标题自动优化
                //$seo_keyword=yuminew::autoseo($title, $yuming_id);
                //同义词替换
                $filecontent = yuminew::replace_word($filecontent, $yuming_id);

                //关键词优化
                $seod['title'] = $title;
                $seod['body'] = $filecontent;
                $arr_words = yumi::get_words_lists(10, $yuming_id);

                $seod = yumi::seoword($seod, $yuming_id, $arr_words);
                $title = $seod['title'];
                $filecontent = $seod['body'];
                //自动优化keyword
                $keywords_tags = yumi::autokeywords($seod, $yuming_id, $arr_words);
                $seo_keyword = $keywords_tags['keyword'];
                //取出图片存入数据库
                if (preg_match('#src="([^"]*)"#', $filecontent, $nt)) {
                    $thumb = $nt[1];
                } else {
                    $thumb = '';
                }
                $addtime = time();
                //文章标记
                $flag = '';
                if ($addtime % 7 == 0) {
                    $flag = "h";   //头条
                } elseif ($addtime % 11 == 0) {
                    $flag = "c";   //推荐
                } elseif ($addtime % 17 == 0) {
                    $flag = "a";   //推荐
                } elseif ($thumb && $addtime % 3 == 0) {
                    $flag = "f";   //推荐
                }
                $title = strip_tags($title);
                $title = addslashes($title);
                $seo_keyword = addslashes($seo_keyword);
                $keyword = addslashes($keywords_tags['keyword']);
                db::query("insert into `content_{$yuming_id}`(title,flag,source,thumb,status,description,addtime,class,seo_keyword,keyword,oldtitle)  values ('$title','$flag','','$thumb','1','$description','$addtime','$class','$seo_keyword','$keyword','$oldtitle')");
                $id = db::insert_id();
                //自动添加tag
                $this->insert_tags($keywords_tags['tags'], $yuming_id, $id);
                //将文章内容存入文件
                ymcms::article_write($yuming_id, $id, $filecontent);
                db::query("update `caiji` set status=1 where id='$aid'");
                jsc::write_caiji_cache($value);
                $lcount++;
            } catch (Exception $ex) {
                db::query("update `caiji` set status=2 where id='$aid'");
                $errorCount++;
                logging_run('任务出错：' . $ex->getMessage() . ',出错节点：' . json_encode($aid));
                continue;
            }
        }
        //百度主动推送
        foreach ($yuming_arr as $yuid) {
            yumi::baidu_push($yuid, $limit);
        }
        logging_run('完成一次任务，成功：' . $lcount.'，重复：'.$congCount.'，错误：'.$errorCount);
    }

    //查找所属域名和分类
    protected function find_class($text, $classes) {
        $all_t = [];
        $pre_t = [];
        if (empty($text)) {
            $k = array_rand($classes);
            return $classes[$k];
        }
        foreach ($classes as $v) {
            if ($v['title'] == $text) {
                $all_t[] = $v;
            } elseif (strpos($v, $text) > 0) {
                $pre_t[] = $v;
            }
        }
        if (!empty($all_t)) {
            $re = $all_t;
        } elseif (!empty($pre_t)) {
            $re = $pre_t;
        } else {
            $re = $classes;
        }
        $k = array_rand($re);
        return $re[$k];
    }

    private function insert_tags($tags, $yuming_id, $content_id) {
        db::query("delete from tagindex_{$yuming_id} where aid='$content_id'");
        if (!empty($tags)) {
            $time = time();
            $tagstr = implode("','", $tags);
            $res = db::select("select id,tagsname from tagslist_{$yuming_id} where tagsname in ('$tagstr') AND yuming_id='$yuming_id'");
            $oldtags = array();
            foreach ($res as $v) {
                $oldtags[] = $v['tagsname'];
            }
            foreach ($tags as $key => $value) {
                if (!in_array($value, $oldtags)) {
                    db::query("insert into tagslist_{$yuming_id} (tagsname,addtime,yuming_id) values('$value', '$time','$yuming_id') ");
                }
            }
            db::query("insert into tagindex_{$yuming_id} (aid,tagid) select '$content_id',id from tagslist_{$yuming_id} where tagsname in ('$tagstr') AND yuming_id='$yuming_id'");
        }
    }

}
